<template>
  <div class="box cartBox">
    <van-nav-bar
      title="购物车"
      right-text="订单"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push('/order')"
    />
    <div class="cont" v-if="cartList.length < 1">
      空状态
    </div>
    <div class="cont" v-else>
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @edit="onEdit"
      />
      <transition-group name="move">
        <van-swipe-cell v-for="item in cartList" :key="item.proId">
          <van-card
            :price="item.price"
            class="goods-card"
          >
            <template #title>
              <h4 @click="$router.push({name:'Abc',params:{qwe:item.proId}})">{{item.proName}}</h4>
            </template>
            <template #num>
              <van-stepper v-model="item.num" theme="round" button-size="22" disable-input min="1" max="10" @change="onChangeNum(item.proId, item.num)" />
            </template>
            <template #thumb>
              <van-checkbox v-model="item.flag" @change="onChangeFlag(item.proId, item.flag)"></van-checkbox>
              <van-image
                fit="cover"
                :src="item.proImg"
                @click="$router.push('/detail/'+item.proId)"
              />
            </template>
          </van-card>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="onDel(item.proId)" />
          </template>
        </van-swipe-cell>
      </transition-group>
    </div>
    <van-submit-bar :price="flagPrice*100" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="allFlag">全选</van-checkbox>
      <template #tip>
        当前购物车一共有<span>{{$store.getters.sum}}</span>件商品，选中了<span>{{flagNum}}</span>件
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, SwipeCell, Button, AddressList, Stepper, Image as VanImage, Checkbox, SubmitBar, Toast } from 'vant'
import { getCart, setNum, setFlag, delCart, setAllFlag, addOrder } from '@/request/index'
import { mapState } from 'vuex'
import myMixin from '@/mixin/index.js'

Vue.use(NavBar)
Vue.use(SwipeCell)
Vue.use(Button)
Vue.use(AddressList)
Vue.use(Stepper)
Vue.use(Checkbox)
Vue.use(VanImage)
Vue.use(SubmitBar)
Vue.use(Toast)

export default {
  beforeRouteEnter (to, from, next) {
    next((vm) => {
      if (vm.isLogin === 'ok') {
      } else {
        next('/login?to=' + to.path)
      }
    })
  },
  created () {
    console.log('这是组件内部的created')
    this.sayHello()
  },
  mixins: [myMixin],
  data () {
    return {
      chosenAddressId: '1',
      list: [
        {
          id: '1',
          name: '张三',
          tel: '13000000000',
          address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室',
          isDefault: true
        }
      ],
      cartList: []
    }
  },
  mounted () {
    getCart().then(data => {
      // 观察数据,解析数据
      // console.log(data.data.data)
      this.cartList = data.data.data.proData
      // this.$store.commit('cart/change_cartList', this.cartList)
      this.change_cartList(this.cartList)
    })
  },
  methods: {
    sayHello () {
      console.log('这是组件内部的hello')
    },
    onEdit () {},
    onSubmit () {
      const that = this
      // 选择购物车中被选中的商品
      const arr = this.cartList.filter(val => val.flag)
      // console.log(arr)
      // 调用添加订单接口
      addOrder({
        proData: JSON.stringify(arr),
        address: JSON.stringify(this.list[0]),
        state: 1
      }).then(data => {
        // 处理添加之后的去向
        Toast({
          message: '提交订单成功',
          onClose () {
            that.$router.push('/order')
          }
        })
      })
    },
    onChangeNum (id, num) {
      setNum({
        proId: id,
        num: num
      }).then(data => {
        // console.log(data.data)
        Toast('修改成功')
      })
    },
    onChangeFlag (id, flag) {
      setFlag({
        proId: id,
        flag: Number(flag)
      }).then(data => {
        // console.log(data.data)
        Toast('修改成功')
      })
    },
    onDel (id) {
      delCart({
        proId: id
      }).then(data => {
        // console.log(data.data)
        Toast('删除成功')
        let i = 0
        this.cartList.some((val, idx) => {
          i = idx
          return val.proId === id
        })
        this.cartList.splice(i, 1)
      })
    }
  },
  computed: {
    ...mapState({
      isLogin: state => state.login.isLogin
    }),
    allFlag: {
      get () {
        return this.cartList.every(val => val.flag)
      },
      set (v) {
        // console.log(v)
        setAllFlag({
          flag: Number(v)
        }).then(data => {
          this.cartList.forEach(val => {
            val.flag = v
          })
        })
      }
    },
    flagPrice () {
      // 计算被选中商品的总价
      return this.cartList.reduce((prev, val) => {
        return val.flag ? prev + val.price * val.num : prev
      }, 0)
    },
    // allNum () {
    //   return this.cartList.reduce((prev, val) => {
    //     return prev + val.num
    //   }, 0)
    // },
    flagNum () {
      return this.cartList.reduce((prev, val) => {
        return val.flag ? prev + val.num : prev
      }, 0)
    }
  }
}
</script>

<style lang="scss">
.cartBox{
  .cont{
    .van-address-list{
      height: auto;
      padding: 12px;
      .van-address-list__bottom{
        display: none;
      }
    }
    .goods-card {
      margin: 0;
      background-color: white;
      .van-card__thumb{
        width: 1.1rem;
        display: flex;
        align-items: center;
        .van-image{
          width: 0.8rem;
          margin-left: 0.1rem;
        }
      }
      .van-card__content{
        h4{
          line-height: 20px;
          height: 40px;
          overflow: hidden;
        }
      }
    }
    .delete-button {
      height: 100%;
    }
  }
  .van-submit-bar{
    .van-submit-bar__tip{
      span{
        font-size: 30px;
        font-weight: bold;
      }
    }
  }
}

// .move-enter{}
// .move-enter-active{}
// .move-enter-to{}
.move-leave{
  transform: translate(0);
  opacity: 1;
}
.move-leave-active{
  transition: all 0.5s;
}
.move-leave-to{
  transform: translate(100vw);
  opacity: 0;
}

</style>
